package com.yinshi;

import com.jfinal.plugin.activerecord.Db;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;

public class IpServerHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws  Exception{
//    discard

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws  Exception{
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        java.lang.String clientIP = insocket.getAddress().getHostAddress();
        int  clientPort = insocket.getPort();
//        System.out.println("CameraIP:"+clientIP+ "  port:"+clientPort+"\n");
//      System.out.println("msg:"+ msg.toString()+"\n");
        ByteBuf in = (ByteBuf) msg;

        try {
//            while (in.isReadable()) { // (1)
//                System.out.print((char) in.readByte());
//                System.out.flush();
//            }
            Charset utf8 = Charset.forName("UTF-8");

            int i = in.indexOf(0,60,(byte)'#');
            ByteBuf cameraname = in.copy(21,i-21);
//            System.out.println("Camera Name:"+ cameraname.toString(utf8)+"\n");

            ByteBuf serial =in.copy(i+4,35);
//            System.out.println("Camera Serial:"+ serial.toString(utf8)+"\n");
//
//            byte[] barray = new byte[in.readableBytes()];
//            in.getBytes(0,barray);
//            System.out.println(new java.lang.String(barray)+"\n");
//            System.out.println(Arrays.toString(barray)+"\n");
              Myip myip =Myip.idDao.findById(serial.toString(utf8));
              if(myip==null){
                  new Myip().set("sn",serial.toString(utf8)).set("ip",clientIP).set("name",cameraname.toString(utf8)).save();
              }else{
                 Db.update("update ipcamera set ip=? ,lastupdate= now() where sn=?",clientIP,serial.toString(utf8));
                 /*if(myip.set("ip",clientIP).update()){
                     System.out.println("update camera:"+ serial.toString(utf8)+"  ip:"+clientIP+"  Success!");
                 }*/

              }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
            ctx.close();

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
//  Close the connection when an exception is raised.

        cause.printStackTrace();
        ctx.close();
    }

}
